package com.mep.rbac.security;

import com.mep.rbac.model.SysUser;
import com.mep.rbac.service.SysUserService;
import com.mep.rbac.utils.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

//@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserService sysUserService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String password = (String) authentication.getCredentials();
        String username = (String) authentication.getPrincipal();
        SysUser sysUser = sysUserService.findByName(username);
        UserDetails userDetails = userService.loadUserByUsername(username);
        //SysUser sysUser = (SysUser) FastJsonUtils.convertJSONToObject(userDetails.getUsername(), SysUser.class);

        if (PasswordUtils.matches(sysUser.getSalt(), password, userDetails.getPassword())) {
            return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), userDetails.getAuthorities());
//            return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), authentication.getCredentials(), userDetails.getAuthorities());
        }
        // 没有通过认证则抛出密码错误异常
        throw new BadCredentialsException("Bad Credentials");
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
